package pri.jz.keeper.db
import androidx.sqlite.db.SupportSQLiteDatabase



import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.Migration
import pri.jz.keeper.R
import pri.jz.keeper.db.convert.BitmapConvert
import pri.jz.keeper.db.convert.DataConvert
import pri.jz.keeper.entity.User

/**
 *Author by: JZ
 *Email: 2451756617@qq.com
 *PS:Room工厂
 */
@Database(entities = [User::class], version = 1)
@TypeConverters(DataConvert::class, BitmapConvert::class)
abstract class AppDatabase : RoomDatabase(){
    abstract fun userDao(): UserDao
    companion object {
        private const val TAG = "MyDatabase"

        @Volatile private var INSTANCE: AppDatabase? = null

        fun getIns(context: Context): AppDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(context.applicationContext,
                AppDatabase::class.java, context.getString(R.string.room_table_name))
                .fallbackToDestructiveMigration()
                .build()

        private val MIGRATION2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE user ALTER COLUMN sex varchar(4)")
                database.execSQL("update user set sex = '外星人'")
            }
        }
    }

}